/*
 * @(#)EchoServer.java 0.1.0 01/29/2012
 * Copyright(c) CS5321
 * Baylor University, Waco, Texas, U.S.A
 * All Rights Reserved.
 */

package edu.baylor.websocket;

import java.io.IOException;


public class EchoServer implements Runnable {
    
    private IWebSocket webSocket;
 
    /**
     * Class EchoServer constructor method
     * @param webSocket2 from which WebSocket send and receive message;
     */
    public EchoServer(IWebSocket webSocket) {
        this.webSocket = webSocket;
    }

    @Override
    public void run() {
        IWSMessage msg;
    
        try {
            while (true) {
                msg = webSocket.receiveMessage();
                webSocket.sendMessage(msg);
            }
        } catch (Exception e) {
            try {
                webSocket.closeConnection();
            } catch (WSException e1) {
                System.out.println(e1);
            }
        }
    }
    
    
    public static void main(String[] args) {
        
        ServerWebSocket servWebSock = null;
        
        try {
            servWebSock = new ServerWebSocket(5555,0);  
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("servWebSock accept error");
        }
        
        while (true) {     
            try {
                IWebSocket webSocket= servWebSock.accept();
        
                System.out.println("WebSock accepted!");
                
                // Spawn thread to handle new connection
                Thread thread = new Thread(new EchoServer(webSocket));
                thread.start();
            } catch (IOException e) {
                System.out.println("Error in creat client service");
            }
        }
    }
}
